package com.zbf.service;

import com.alibaba.fastjson.JSON;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.query.spi.NativeQueryImplementor;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/6/25  10:58
 * 描述:
 */
@Component
public class TestService {

    @Autowired
    private EntityManager entityManager;

    @Transactional
    public void testDamic(Map<String,String> map){

        String sql="select * from jpa_user where 1=1 ";
        String countSql="select count(1) cous from jpa_user where 1=1 ";

        StringBuffer stringBuffer=new StringBuffer(sql);
        StringBuffer countSqlBuffer=new StringBuffer(countSql);

        if(map.get("userName")!=null&&!"".equals(map.get("userName"))){
            stringBuffer.append(" and user_name like CONCAT('%','"+map.get("userName")+"','%') ");
            countSqlBuffer.append(" and user_name like CONCAT('%','"+map.get("userName")+"','%') ");
        }
        if(map.get("password")!=null&&!"".equals(map.get("password"))){
            stringBuffer.append(" and password="+map.get("password"));
            countSqlBuffer.append(" and password="+map.get("password"));
        }

        Integer startNO=Integer.valueOf(map.get("pageNo"))*Integer.valueOf(map.get("pageSize"))+1;

        stringBuffer.append(" limit "+startNO+","+Integer.valueOf(map.get("pageSize")));

        Session unwrap = entityManager.unwrap(Session.class);

        NativeQuery nativeQuery = unwrap.createNativeQuery(stringBuffer.toString());

        List<Map<String,Object>> resultList = nativeQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();

        Object singleResult = unwrap.createNativeQuery(countSqlBuffer.toString()).getSingleResult();


        System.out.println("list:=="+JSON.toJSONString(resultList));
        System.out.println("count:=="+singleResult);

    }

}
